#include "TcpConnect.h"

TcpConnect::TcpConnect(boost::asio::io_context& ioc)
    :m_socket(ioc)
{
    std::cout << "create tcp connect success\n\n";
}

std::shared_ptr<TcpConnect> TcpConnect::create(boost::asio::io_context& ioc)
{
    return std::shared_ptr<TcpConnect>(new TcpConnect(ioc));
}

void TcpConnect::start()
{
    std::cout << "start write...\n\n";
    m_msg = "hello world";
    boost::asio::async_write(m_socket, boost::asio::buffer(m_msg),
        [self = shared_from_this()](const boost::system::error_code& ec, size_t len)
        {
            self->handleWrite(ec, len);
        });
}

void TcpConnect::handleWrite(const boost::system::error_code& ec, size_t len)
{
    if (!ec)
    {
        std::cout << "成功发送 message : " << m_msg << "    len : " << len << " 字节数据\n\n";

    }
    else
    {
        // 根据错误类型进行详细处理
        if (ec == boost::asio::error::operation_aborted) {
            std::cerr << "发送操作被取消: 可能是连接关闭或io_context停止" << std::endl;
        }
        else if (ec == boost::asio::error::eof) {
            std::cerr << "连接被对端关闭" << std::endl;
        }
        else if (ec == boost::asio::error::connection_reset) {
            std::cerr << "连接被对端重置" << std::endl;
        }
        else if (ec == boost::asio::error::timed_out) {
            std::cerr << "发送操作超时" << std::endl;
        }
        else if (ec == boost::asio::error::no_buffer_space) {
            std::cerr << "发送缓冲区已满" << std::endl;
        }
        else if (ec == boost::asio::error::broken_pipe) {
            std::cerr << "连接管道已断开" << std::endl;
        }
        else {
            std::cerr << "发送错误 [" << ec.value() << "]: " << ec.message() << std::endl;
        }

        // 关闭socket
        if (m_socket.is_open())
        {
            boost::system::error_code ignore_ec;
            m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore_ec);
            m_socket.close(ignore_ec);
        }
    }
}

boos